package com.aidansmeaton.weightmanager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.CalorieHelper;
import com.quietlycoding.android.picker.NumberPicker;

/** The first activity in the app. */
public class DiaryWeightActivity extends Activity {
	
	private static final int MILLIS_IN_DAY = 86400000;
	private static final int POUNDS_IN_STONE = 14;
	private static final double POUNDS_IN_KILO = 2.2f;
	private static final double KILOS_IN_POUND = 0.4536F;
	private static final int MAX_POUNDS = 13;
	private static final int MAX_STONES = 100;
	private static final int MAX_KILOS = 199;
	private static final int MIN_POUNDS = 0;
	private static final int MIN_STONES = 0;
	private static final int MIN_KILOS = 0;
	
	private DatabaseHelper db;
	private String date;
	private boolean imperial;			// global
	private boolean imperialRecord;		// this record only
	private int weight;
	private int daysSinceLastRecording;
	
	private TextView stonesText;
	private TextView poundsText;
	private TextView kilosText;
	private TextView agoText;
	private TextView lost;
	private TextView left;
	private ProgressBar progress;	
	private ImageButton add;	
	private ImageButton edit;	

	private LinearLayout imperialView;
	private LinearLayout metricView;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_weight);
        
        db = DatabaseHelper.getInstance(this);
        date = this.getIntent().getStringExtra("Date");
        imperial = getSharedPreferences("Profile",0).getBoolean("Imperial", true);
        
        // Identify textviews
		lost = (TextView) findViewById(R.id.weight_lost_text);
		left = (TextView) findViewById(R.id.weight_remaining_text);
		
		metricView = (LinearLayout) findViewById(R.id.metric);
		imperialView = (LinearLayout) findViewById(R.id.imperial);
		
		stonesText = (TextView) findViewById(R.id.current_stones_text);
		poundsText = (TextView) findViewById(R.id.current_pounds_text);
		kilosText = (TextView) findViewById(R.id.current_kg_text);
		
		agoText = (TextView) findViewById(R.id.days_ago_text);
		progress = (ProgressBar) findViewById(R.id.progressBar);
		
		add = (ImageButton) findViewById(R.id.add);
		edit = (ImageButton) findViewById(R.id.edit);
		
		/*
		// Get info about goal
		int start = Integer.parseInt(cursor.getString(DatabaseHelper.GOAL_LOG_STARTVALUE));
		int current = Integer.parseInt(cursor.getString(DatabaseHelper.GOAL_LOG_CURRENTVALUE));
		int end = Integer.parseInt(cursor.getString(DatabaseHelper.GOAL_LOG_ENDVALUE));
		
		// Fill text view with cursor values
		goal.setText(getString(R.string.lose)+" "+(start-end)+" "+getString(R.string.kg));
		lost.setText((start-current)+" "+getString(R.string.kg));
		left.setText((current-end)+" "+getString(R.string.kg));    
		*/
        
	}
    
    @Override 
    public void onResume(){
    	super.onResume();
    	
    	// refresh date
    	date = this.getIntent().getStringExtra("Date");
    	
    	// refresh weight
    	Cursor cursor = db.getWeightLogsBeforeDate(date);
    	
    	// a weight has been recorded
    	if (cursor.getCount() > 0){
    		
    		cursor.moveToFirst();
    		Cursor first = db.getWeightLogs(true);
    		first.moveToFirst();
    		
    		
    		// Set Text In Main View
    		
    		int current_weight = cursor.getInt(DatabaseHelper.WEIGHT_LOG_WEIGHT);
    		String units = cursor.getString(DatabaseHelper.WEIGHT_LOG_COMMENT);
    		imperialRecord = units.equals("i");
    		weight = current_weight;
    		
    		int target_weight = getSharedPreferences("Profile", 0).getInt("TargetWeight",-1);
    		boolean target_imperial = getSharedPreferences("Profile", 0).getBoolean("TargetUnits",true);
    		
    		int first_weight = first.getInt(DatabaseHelper.WEIGHT_LOG_WEIGHT);
    		String first_units = first.getString(DatabaseHelper.WEIGHT_LOG_COMMENT);
    		boolean first_imperial = first_units.equals("i");
    		
    		if (imperialRecord){
    			metricView.setVisibility(View.GONE);
    			imperialView.setVisibility(View.VISIBLE);
    			stonesText.setText("" + weight/POUNDS_IN_STONE);
        		poundsText.setText("" + weight%POUNDS_IN_STONE);
    		} else {
    			metricView.setVisibility(View.VISIBLE);
    			imperialView.setVisibility(View.GONE);
    			kilosText.setText("" + weight);
    		}    		
    		
    		// Set Text In Header
    		
    		// convert metric start weight to imperial
    		if (imperial && !imperialRecord){
    			current_weight = ((int)(current_weight * POUNDS_IN_KILO));
    		}    		
    		// convert metric start weight to imperial
    		if (imperial && !first_imperial){
    			first_weight = ((int)(first_weight * POUNDS_IN_KILO));
    		}
    		// convert metric start weight to imperial
    		if (imperial && !target_imperial){
    			target_weight = ((int)(target_weight * POUNDS_IN_KILO));
    		}
    		
    		// convert imperial start weight to metric
    		if (!imperial && imperialRecord){
    			current_weight = ((int)(current_weight * KILOS_IN_POUND));
    		}
    		// convert imperial start weight to metric
    		if (!imperial && first_imperial){
    			first_weight = ((int)(first_weight * KILOS_IN_POUND));
    		}
    		// convert imperial start weight to metric
    		if (!imperial && target_imperial){
    			target_weight = ((int)(target_weight * KILOS_IN_POUND));
    		}
    		
    		agoText.setText("");
    		
    		progress.setMax(first_weight - target_weight);
    		progress.setProgress(first_weight - current_weight);	
    		//String goal = (target_weight/POUNDS_IN_STONE+" stone, "+target_weight%POUNDS_IN_STONE+" pounds");
    		lost.setText(CalorieHelper.weightToString((first_weight-current_weight), imperial));
    		if (first_weight-current_weight > 0) lost.setTextColor(getResources().getColor(R.color.green1));
    		left.setText(CalorieHelper.weightToString((current_weight-target_weight), imperial));
    		
    		String datestring = cursor.getString(DatabaseHelper.WEIGHT_LOG_TIME);
    		datestring = datestring.substring(0, 10);	// ensures it's formatted "yyyy-MM-dd"
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		
    		try {
    			Date date1 = sdf.parse(date);
    			Date date2 = sdf.parse(datestring);
    			long diaryDate = date1.getTime();
    			long lastLoggedDate = date2.getTime();
    			long diff = diaryDate - lastLoggedDate;
    			daysSinceLastRecording = (int) (diff / MILLIS_IN_DAY);
    			    			
    			if (daysSinceLastRecording == 0){
    				agoText.setVisibility(View.INVISIBLE);
    				add.setVisibility(View.GONE);
    				edit.setVisibility(View.VISIBLE);
    			} else {
    				agoText.setVisibility(View.VISIBLE);
    				agoText.setText(getString(R.string.diary_weight_recorded) + " " +
        					daysSinceLastRecording + " " + getString(R.string.diary_weight_days_before));
    				add.setVisibility(View.VISIBLE);
    				edit.setVisibility(View.GONE);
    			}
    			
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	// a weight has not been recorded before this date
    	else {
    		weight = -1;
    		metricView.setVisibility(View.GONE);
			imperialView.setVisibility(View.GONE);
    		agoText.setText("No weight records were kept before this date.");
    	}
		
    }
    
    private void recordImperialWeight(){
    	
    	// initialise dialog
    	final Dialog d = new Dialog(this);
    	d.setContentView(R.layout.dialog_record_weight_imperial);
    	    	
    	// force width to fill parent
    	LayoutParams params = d.getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    	
        // identify number pickers - set limits
    	final NumberPicker pStones = (NumberPicker) d.findViewById(R.id.stones_picker);
    	final NumberPicker pPounds = (NumberPicker) d.findViewById(R.id.pounds_picker);
    	int lastWeight = (!imperialRecord) ? ((int)(weight*POUNDS_IN_KILO)) : (weight);
    	pStones.setRange(MIN_STONES, MAX_STONES);
    	pPounds.setRange(MIN_POUNDS, MAX_POUNDS);
    	pStones.setCurrent(lastWeight/POUNDS_IN_STONE);
    	pPounds.setCurrent(lastWeight%POUNDS_IN_STONE);
    	
    	// identify buttons
    	final Button okay = (Button) d.findViewById(R.id.okay_button);
    	final Button cancel = (Button) d.findViewById(R.id.cancel_button);
    	final Button remove = (Button) d.findViewById(R.id.remove_button);
    	
    	if (daysSinceLastRecording == 0){
    		d.setTitle(getString(R.string.diary_weight_edit_your_weight));
    		remove.setEnabled(true);
    		remove.setClickable(true);
    	} else {
    		d.setTitle(getString(R.string.diary_weight_record_your_weight));
    	}
    	
    	// set listener for okay button
    	okay.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int stones = pStones.getCurrent();
				int pounds = pPounds.getCurrent();
				int weight = (stones * POUNDS_IN_STONE) + pounds;
				db.editWeightLog(DiaryWeightActivity.this.date, weight, "i");
				d.dismiss();
				DiaryWeightActivity.this.onResume();
			}
    	});
    	
    	// set listener for cancel button
    	cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				d.dismiss();
			}
    	});
    	
    	// set listener for remove button
    	remove.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				final Dialog dialog = new Dialog(v.getContext());
		    	dialog.setContentView(R.layout.dialog_remove);
		    	dialog.setTitle("Remove Weight Record?");
		    	dialog.setCancelable(true);
		    	
		    	// force width to fill parent
		    	LayoutParams params = dialog.getWindow().getAttributes(); 
		        params.width = LayoutParams.FILL_PARENT; 
		        dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
		        
		        Button cancel = (Button) dialog.findViewById(R.id.cancel);
		        cancel.setOnClickListener(new OnClickListener() {
		            public void onClick(View v) {
		            	dialog.dismiss();
		            }
		        });    	
		    
		        Button remove = (Button) dialog.findViewById(R.id.remove);
		        remove.setOnClickListener(new OnClickListener() {
		            public void onClick(View v) {
		            	dialog.dismiss();
		            	db.removeWeightLogsForDate(DiaryWeightActivity.this.date);
		            	DiaryWeightActivity.this.onResume();
		            	d.dismiss();
		            }
		        });
		        
		        dialog.show();
			}
    	});
    	
    	d.show();
    	
    }
    
    private void recordMetricWeight(){
    	
    	// initialise dialog
    	final Dialog d = new Dialog(this);
    	d.setContentView(R.layout.dialog_record_weight_metric);
    	    	
    	// force width to fill parent
    	LayoutParams params = d.getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    	
        // identify number pickers - set limits
    	final NumberPicker pKilos = (NumberPicker) d.findViewById(R.id.kg_picker);
    	pKilos.setRange(MIN_KILOS, MAX_KILOS);
    	int lastWeight = (imperialRecord) ? ((int)(weight*KILOS_IN_POUND)) : (weight) ;
    	pKilos.setCurrent(lastWeight);
    	
    	// identify buttons
    	final Button okay = (Button) d.findViewById(R.id.okay_button);
    	final Button cancel = (Button) d.findViewById(R.id.cancel_button);
    	final Button remove = (Button) d.findViewById(R.id.remove_button);
    	
    	if (daysSinceLastRecording == 0){
    		d.setTitle(getString(R.string.diary_weight_edit_your_weight));
    		remove.setEnabled(true);
    		remove.setClickable(true);
    	} else {
    		d.setTitle(getString(R.string.diary_weight_record_your_weight));
    	}
    	
    	// set listener for okay button
    	okay.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int kg = pKilos.getCurrent();
				db.editWeightLog(DiaryWeightActivity.this.date, kg, "m");
				d.dismiss();
				DiaryWeightActivity.this.onResume();
			}
    	});
    	
    	// set listener for cancel button
    	cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				d.dismiss();
			}
    	});
    	
    	// set listener for remove button
    	remove.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				final Dialog dialog = new Dialog(v.getContext());
		    	dialog.setContentView(R.layout.dialog_remove);
		    	dialog.setTitle("Remove Weight Record?");
		    	dialog.setCancelable(true);
		    	
		    	// force width to fill parent
		    	LayoutParams params = dialog.getWindow().getAttributes(); 
		        params.width = LayoutParams.FILL_PARENT; 
		        dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
		        
		        Button cancel = (Button) dialog.findViewById(R.id.cancel);
		        cancel.setOnClickListener(new OnClickListener() {
		            public void onClick(View v) {
		            	dialog.dismiss();
		            }
		        });    	
		    
		        Button remove = (Button) dialog.findViewById(R.id.remove);
		        remove.setOnClickListener(new OnClickListener() {
		            public void onClick(View v) {
		            	dialog.dismiss();
		            	db.removeWeightLogsForDate(DiaryWeightActivity.this.date);
		            	DiaryWeightActivity.this.onResume();
		            	d.dismiss();
		            }
		        });
		        
		        dialog.show();
			}
    	});
    	
    	d.show();
    	
    }

	public void recordWeightClick(View v){
		
		if (daysSinceLastRecording == 0){
			if (imperialRecord){
				recordImperialWeight();
			} else {
				recordMetricWeight();
			}
		} else {
			if (imperial){
				recordImperialWeight();
			} else {
				recordMetricWeight();
			}
		}		  	
    }    
}